package org.mcflier.appuntamento.tasks;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.mcflier.appuntamento.core.Factory;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.core.logger.LoggerManager;

public abstract class AbstractTask extends Thread {
        
        private long delay;
        protected Logger logger;
        protected boolean isStopped;
        protected Map<String, String> arguments;
        
        public AbstractTask(String name, long delay) throws ModulesException{
                if(name==null)
                        throw new NullPointerException("Task name must not be null");
                
                if(delay<0)
                        throw new IllegalArgumentException("Delay must be equal or greater than zero");
                
                this.setName(name);
                this.delay = delay;
                this.logger = ((LoggerManager)Factory.getInstance().getModuleInstance(Factory.MODULE_LOGGER)).getLogger(this.getClass().getName());
                this.isStopped = true;
                this.arguments = new HashMap<String, String>();
        }
        
        public void addArgument(String key, String value){
                this.arguments.put(key, value);
        }
        
        protected String getArgument(String key){
                return this.arguments.get(key);
        }

        public long getDelay() {
                return delay;
        }
        
        public boolean isStopped(){
                return this.isStopped;
        }
        
        @Override
        public void run(){
                this.isStopped = false;
                while(!this.isStopped){
                        try {
                                synchronized (this) {
                                        this.doSomething();
                                        this.wait(this.delay);
                                }
                        } catch (InterruptedException e) {
                                this.logger.warning("Error delaying the task '"+this.getName()+"'");
                        }
                }
                this.logger.info("Task '"+this.getName()+"' stopped");
        }
        
        public void stopTask(){
                this.isStopped=true;
                synchronized (this) {
                        this.notify();
                }
        }

        public abstract void doSomething();
}